import React, { useCallback } from 'react';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import './customComponents.css';

interface CustomButtonProps {
  children: React.ReactNode;
  onClick?: () => void;
  loading?: boolean;
  icon?: React.ReactNode;
  type?: 'primary' | 'default' | 'danger' | 'secondary' | 'ghost' | 'link' | 'dashed';
  className?: string;
  size?: 'tiny' | 'small' | 'default' | 'large' | 'xlarge';
  disabled?: boolean;
  block?: boolean;
  shape?: 'default' | 'circle' | 'round';
  htmlType?: 'button' | 'submit' | 'reset';
  title?: string;
  style?: React.CSSProperties;
}

const CustomButton: React.FC<CustomButtonProps> = ({ 
  children, 
  onClick, 
  loading = false, 
  icon, 
  type = 'default',
  className = '',
  size = 'default',
  disabled = false,
  block = false,
  shape = 'default',
  htmlType = 'button',
  title,
  style
}) => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);

  // 使用 useCallback 优化事件处理函数
  const handleClick = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    if (!disabled && !loading && onClick) {
      onClick();
    }
  }, [disabled, loading, onClick]);

  // Determine button classes
  const getButtonClasses = () => {
    const classes = ['custom-button', size, type];
    
    if (shape === 'circle' || shape === 'round') {
      classes.push('round');
    }
    
    if (disabled || loading) {
      classes.push('disabled');
    }
    
    if (block) {
      classes.push('block');
    }
    
    if (className) {
      classes.push(className);
    }
    
    return classes.join(' ');
  };

  // Determine spinner classes
  const getSpinnerClasses = () => {
    const classes = ['spinner'];
    
    if (icon) {
      classes.push('mr-2');
    }
    
    return classes.join(' ');
  };

  const isDisabled = disabled || loading;

  return (
    <button
      type={htmlType}
      onClick={handleClick}
      disabled={isDisabled}
      title={title}
      style={style}
      className={getButtonClasses()}
    >
      {loading ? (
        <div className={getSpinnerClasses()} />
      ) : icon && <span className="mr-2">{icon}</span>}
      {children}
    </button>
  );
};

export default CustomButton;